package com.gt.ao.views;

import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.InputStream;

/**
 * @author gt.ao
 */
public class ImgPanel extends Panel {
      
    private final Image screenImage = new BufferedImage(800, 800, 2);
      
    private final Graphics2D screenGraphic = (Graphics2D) screenImage.getGraphics();
      
    private Image backgroundImage;  
      
    public ImgPanel() {
        ImageIcon icon = new ImageIcon(ClassLoader.getSystemResource("7891.png"));
        backgroundImage = icon.getImage();
        this.repaint();
        // 设定焦点在本窗体  
        setFocusable(true);  
        // 设定初始构造时面板大小,这里先采用图片的大小  
        setPreferredSize(new Dimension(800,800));
        // 绘制背景  
        drawView();  
    }

    /** 
     * 载入图像 
     */  
    public void reloadImage(byte[] filePath) {
        //获得当前类对应的相对位置image文件夹下的背景图像  
        ImageIcon icon = new ImageIcon(filePath);
        //将图像实例赋给backgroundImage  
        backgroundImage = icon.getImage();
        this.repaint();
    }

    private void drawView() {
        screenGraphic.drawImage(backgroundImage, 0, 0, null);
    }

    @Override
    public void paint(Graphics g){
        ImageIcon i = new ImageIcon(backgroundImage);
        //此处是重点，通过this获取窗体大小来设置图片
        i.setImage(backgroundImage.getScaledInstance(this.getWidth(),this.getHeight(),Image.SCALE_AREA_AVERAGING));
        //绘制图片
        g.drawImage(i.getImage(), 0, 0, null);
    }

}  